import QRCode from 'qrcode'
// const canvas = document.createElement('canvas');
// canvas.id = 'canvas1';
// canvas.style.width = "500px";
// canvas.style.height = "500px";
// canvas.style.margin = "0 auto";
// document.body.append(canvas);

const html = [
  `<img id="logo" src="img/logo.jpg"></img>`,
  `<img id="result" style="display:none;" />`,
  `<canvas id="canvas1" style="width:500px;height:500px;display:none;"></canvas>`,
  `<div class="form"><br/> 二维码宽度：<input type="text" id="txtW" value="500" />`,
  `<br/> 二维码高度：<input type="text" id="txtH" value="500" />`,
  `<br/> LOGO宽度：<input type="text" id="logoW" value="120" />`,
  `<br/> LOGO高度：<input type="text" id="logoH" value="48" />`,
  `<br/> LOGO_X：<input type="text" id="logoX" value="200" />`,
  `<br/> LOGO_Y：<input type="text" id="logoY" value="220" />`,
  `<br/> 网址：<input type="text" placeholder="如：https://www.baidu.com" id="txtText" />`,
  `<br/><span style="visibility: hidden;">地址：</span><button id="btn">生成二维码</button></div>`,
].join('')
const appEl = document.querySelector('#app')
appEl.innerHTML = html
const canvas = document.querySelector('#canvas1')
const text = document.querySelector('#txtText')
const w = document.querySelector('#txtW')
const h = document.querySelector('#txtH')
const btn = document.querySelector('#btn')
const result = document.querySelector('#result')

const logoW = document.querySelector('#logoW')
const logoH = document.querySelector('#logoH')
const logoX = document.querySelector('#logoX')
const logoY = document.querySelector('#logoY')

//从 canvas 提取图片 image
function convertCanvasToImage (canvas) {
  //新Image对象，可以理解为DOM
  // var image = new Image();
  // canvas.toDataURL 返回的是一串Base64编码的URL
  // 指定格式 PNG
  return canvas.toDataURL("image/png");
  // return image;
}

function CreateQRCode (text, w, h) {
  QRCode.toCanvas(canvas, text, {
    width: w,
    height: h,
    colorDark: "#ffff000",
    colorLight: "#ffffff",
    errorCorrectionLevel: 'H'
  }, (error) => {
    if (error) console.error(error)
    console.log('success!');
  })
  var c = document.getElementById("canvas1");
  var ctx = c.getContext("2d");
  var img = document.getElementById("logo");
  ctx.drawImage(img, logoX.value, logoY.value, logoW.value, logoH.value);

  setTimeout(() => {
    result.src = convertCanvasToImage(canvas)
    result.style.display="block"
  }, 500);
}
btn.onclick = function (e) {
  CreateQRCode(text.value, w.value, h.value)
}

// QRCode.toCanvas(canvas, 'https://v.qq.com/txp/iframe/player.html?vid=c09606rrdvf', {
//   width: 500,
//   height: 500,
//   colorDark: "#ffff000",
//   colorLight: "#ffffff",
//   errorCorrectionLevel: 'H'
// }, (error) => {
//   if (error) console.error(error)
//   console.log('success!');
// })

// canvas, text, [options], [cb(error)]